package com.brush.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.brush.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * mybatisplus自动增充功能( 方法增强)
 */
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {



    /**
     * 数据实体类  @TableField(fill = FieldFill.INSERT)
     * 调用save()
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter("createBy")) {

            if (!SecurityUtils.getAuthentication().getPrincipal().toString().equals("anonymousUser")) {
                this.strictInsertFill(metaObject, "createBy", String.class, SecurityUtils.getUsername());
            }

        }

        if (metaObject.hasGetter("createTime")) {
            this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        }

    }


    /**
     * 数据实体类  @TableField(fill = FieldFill.UPDATE)
     * 调用update() 或updateById()
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {

        if (metaObject.hasGetter("updateBy")) {
            //登录过了
            if (!SecurityUtils.getAuthentication().getPrincipal().toString().equals("anonymousUser")) {
                this.strictUpdateFill(metaObject, "updateBy", String.class, SecurityUtils.getUsername());
            }

        }

        if (metaObject.hasGetter("updateTime")) {
            this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        }
    }
}
